﻿Imports System.Windows.Input
Imports System.Windows.Data

Public Class FileSystemBrowserConverter
    Implements IValueConverter

    Private Class Wrapper
        Implements ICommand

        Dim _mode As String
        Dim _source As VMParametrageElement

        Sub New(ByVal source As VMParametrageElement, ByVal mode As String)
            Me._source = source
            Me._mode = mode
        End Sub

        Public Function CanExecute(ByVal parameter As Object) As Boolean Implements System.Windows.Input.ICommand.CanExecute
            Return True
        End Function

        Public Event CanExecuteChanged(ByVal sender As Object, ByVal e As System.EventArgs) Implements System.Windows.Input.ICommand.CanExecuteChanged

        Public Sub Execute(ByVal parameter As Object) Implements System.Windows.Input.ICommand.Execute
            If _mode = "file" Then
                Dim ofd = New Microsoft.Win32.OpenFileDialog() With {.Multiselect = False, .Filter = "Fichiers EXCEL|*.xls;*.xlsm |Fichiers EXCEL 2003|*.xls|Fichiers EXCEL 2007+|*.xlsm"}
                If ofd.ShowDialog() = True Then
                    _source.Value = ofd.FileName
                End If
            End If
            If _mode = "folder" Then
                Dim ofd = New System.Windows.Forms.FolderBrowserDialog()
                If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    _source.Value = ofd.SelectedPath
                End If

            End If
        End Sub
    End Class

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Try
            If value Is Nothing Then Return Nothing
            Return New Wrapper(value, parameter)
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotImplementedException()
    End Function
End Class